@ECHO OFF

SET STARTDIR=%CD%

IF "%1" == "" GOTO HELP

IF "%1" == "*" (
	FOR /D %%F IN (*) DO (
		CALL %0 %%F
	)
	GOTO EXIT
)

IF NOT EXIST %1 GOTO NOTFOUND

:: Variable setup
SET ROOTDIR=%STARTDIR%\..
SET CC65DIR=%ROOTDIR%\cc65
SET CC=java -jar %ROOTDIR%\uc65.jar
SET CA=%CC65DIR%\ca65.exe
SET LD=%CC65DIR%\ld65.exe
SET NAME=%1
CD %NAME%
IF ERRORLEVEL 1 GOTO NOTFOUND

ECHO Building %NAME%

:: Prep platform files
%CA% ..\..\lib\crt0.s
IF ERRORLEVEL 1 GOTO ERROR

:: Compile all source files
FOR %%F IN (*.uc) DO (
	%CC% -d %%F
	IF ERRORLEVEL 1 GOTO ERROR
)

:: Assemble all source files
FOR %%F IN (*.s) DO (
	%CA% %%F
	IF ERRORLEVEL 1 GOTO ERROR
)

:: Link all binaries
SET OBJS=..\..\lib\crt0.o
FOR %%F IN (*.o) DO (
	SET OBJS=%OBJS% %%F
)

%LD% -o %NAME%.nes --config ..\..\lib\memory.cfg %OBJS%
IF ERRORLEVEL 1 GOTO ERROR

GOTO EXIT

:ERROR
ECHO Build failed
GOTO EXIT

:NOTFOUND
ECHO The project %1 does not exist
GOTO EXIT

:HELP
ECHO Usage: %0 project
ECHO ARGUMENTS
ECHO   project       The name of the project directory to build. If the * is
ECHO                 used as the project name, all projects will be built.
GOTO EXIT

:EXIT
CD %STARTDIR%
